<template>
  <div class="login-panel">
    <!-- 登录面板标题，包含关闭按钮 -->
    <div class="title drag">
      <span>SweetCircle</span>
    </div>
    <!-- 登录表单容器 -->
    <div class="login-form">
      <!-- 使用Element UI的表单组件进行登录注册信息输入 -->
      <el-form :model="fromData" label-width="0px" @submit.prevent>
        <!-- 邮箱输入项 -->
        <!--      输入-->
        <el-form-item>
          <el-input
            v-model.trim="fromData.account"
            clearable
            placeholder="请输入邮箱/甜蜜账号ID"
            size="large"
          >
            <template #prefix>
              <span class="iconfont icon-user"></span>
            </template>
          </el-input>
        </el-form-item>
        <!-- 昵称输入项，仅在注册时显示 -->
        <el-form-item v-if="isLogin === 1">
          <el-input
            v-model.trim="fromData.nickName"
            clearable
            placeholder="请输入昵称"
            size="large"
            @input="VerifyCharacterLength"
          >
            <template #prefix>
              <span class="iconfont icon-user-nick"></span>
            </template>
          </el-input>
        </el-form-item>
        <!-- 密码输入项 -->
        <el-form-item>
          <el-input
            v-model.trim="fromData.password"
            clearable
            placeholder="请输入密码"
            show-password
            size="large"
          >
            <template #prefix>
              <span class="iconfont icon-password"></span>
            </template>
          </el-input>
        </el-form-item>
        <!-- 确认密码输入项，仅在注册时显示 -->
        <el-form-item v-if="isLogin !== 0">
          <el-input
            v-model.trim="fromData.confirmPassword"
            clearable
            placeholder="请输入确认密码"
            show-password
            size="large"
          >
            <template #prefix>
              <span class="iconfont icon-password"></span>
            </template>
          </el-input>
        </el-form-item>
        <!-- 验证码输入项 -->
        <el-form-item>
          <div class="captcha-container">
            <el-input
              v-model.trim="fromData.captcha"
              clearable
              placeholder="请输入验证码"
              size="large"
              @keyup.enter="submit"
            >
              <template #prefix>
                <span class="iconfont icon-checkcode"></span>
              </template>
            </el-input>
            <img :src="captchaPath" class="captcha-img" alt="点击我重新获取" @click="getCaptcha" />
          </div>
        </el-form-item>
        <!-- 登录、注册、重置密码按钮 -->
        <el-form-item>
          <el-button v-if="isLogin === 0" class="login-btn" type="primary" @click="submit"
            >登 录
          </el-button>
          <el-button v-if="isLogin === 1" class="login-btn" type="primary" @click="submit"
            >注 册
          </el-button>
          <el-button v-if="isLogin === 2" class="login-btn" type="primary" @click="submit"
            >重 置 密 码
          </el-button>
        </el-form-item>
      </el-form>
      <!-- QQ登录按钮 -->
      <!--qq登录-->
      <img alt="" class="qq-login" src="../assets/img/qq.png" />
      <!-- 登录/注册/重置密码切换面板 -->
      <div v-if="isLogin === 0" class="row-op-panel">
        <span class="a-link" @click="changeIsLogin(2)">忘记密码</span>&nbsp;|&nbsp;
        <span class="a-link" @click="changeIsLogin(1)">注册账号</span>
      </div>
      <div v-if="isLogin !== 0" class="row-op-panel">
        <span class="a-link" @click="changeIsLogin(0)">已有账号,登录</span>
      </div>
    </div>
  </div>
  <WindowOperation
    :close-type="0"
    :show-max="false"
    :show-min="false"
    :show-set-top="false"
    :cllose-type="0"
  ></WindowOperation>
  <div v-if="dialogTableVisible" class="card2 no-drag">
    <el-card class="info">
      <div>账号在别处登录，是否继续登录</div>
      <div class="button">
        <el-button type="primary" @click="loginSuccess">继续</el-button>
        <el-button type="primary" @click="dialogTableVisible = false">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import WindowOperation from '#/components/WindowOperation.vue'
import { ElLoading, ElMessage } from 'element-plus'
import { clone } from 'es-toolkit'
import Tool from '#/utils/Tool'
import { useContactInfoStore } from '#/stores/ContactInfoStore'
import { useNewFriendStore } from '#/stores/NewFriendStore'
import { useUserInfoStore } from '#/stores/UserInfoStore'
import Api from '#/utils/Api'


const userInfoStore = useUserInfoStore() // 存储联系人信息  用户的所有联系人
const newFriendStore = useNewFriendStore() // 存储联系人信息  用户的所有联系人
const contactInfoStore = useContactInfoStore() // 存储联系人信息  用户的所有联系人
const router = useRouter()
let captchaPath = ref('') // 验证码路径
const dialogTableVisible = ref(false) // 显示卡片账号异地登录 是否强制下线重新登录
let alreadyLoginResponse = ref({})
// 加载前先获取验证码
onMounted(() => {
  getCaptcha()
})
// 登录，注册，修改密码表单
const fromData = ref({
  account: '00@123.com',
  email: '',
  userSweetCircleId: '',
  password: 'zxc123456',
  nickName: '',
  confirmPassword: '',
  captcha: '',
  captchaKey: ''
})

// 控制登录、注册、重置密码状态的引用
const isLogin = ref(0)

//重置表单的数据
const resetFromData = () => {
  fromData.value = {
    account: '',
    email: '',
    userSweetCircleId: '',
    password: '',
    nickName: '',
    confirmPassword: '',
    captcha: '',
    captchaKey: ''
  }
}

// 监听切换登录、注册、重置密码状态
const changeIsLogin = (val) => {
  window.ipcRenderer.send('switchWindow', val)
  resetFromData()
  isLogin.value = val
  getCaptcha()
}
// 获取验证码
const getCaptcha = async () => {
  fromData.value.captcha = ''
  let res = await Api.captcha()
  captchaPath.value = res.data.captchaBase64
  fromData.value.captchaKey = res.data.captchaKey
}
// 点击提交
const submit = () => {
  if (/@[^@]+\.com$/.test(fromData.value.account)) {
    fromData.value.email = fromData.value.account
    fromData.value.userSweetCircleId = null
  } else {
    fromData.value.email = null
    fromData.value.userSweetCircleId = fromData.value.account
  }
  // 登录
  if (isLogin.value === 0) {
    const { res, msg } = Tool.parameterValidation(fromData, 0)
    if (!res) {
      ElMessage.error(msg)
      return
    }
    _login()
    // 注册
  } else if (isLogin.value === 1) {
    const { res, msg } = Tool.parameterValidation(fromData, 1)
    if (!res) {
      ElMessage.error(msg)
      return
    }
    _register()
    // 重置密码
  } else {
    const { res, msg } = Tool.parameterValidation(fromData, 2)
    if (!res) {
      ElMessage.error(msg)
      return
    }
    _resetPassword()
  }
}
// 登录请求后端
const _login = async () => {
  const response = await Api.login(fromData.value)
  if (response.code === 200) {
    // 如果已经登录
    if (response.data.alreadyLogin) {
      dialogTableVisible.value = true
      alreadyLoginResponse.value = response
    } else {
      await loginSuccess(response)
    }
  } else {
    await getCaptcha()
    ElMessage.error(response.msg)
  }
}
//注册请求后端
const _register = async () => {
  const response = await Api.register(fromData.value)
  if (response.code === 200) {
    changeIsLogin(0)
  } else {
    await getCaptcha()
    ElMessage.error(response.msg)
  }
}

// 重置密码逻辑
const _resetPassword = async () => {
  const response = await Api.resetPassword(fromData.value)
  if (response.code === 200) {
    changeIsLogin(0)
  } else {
    await getCaptcha()
    ElMessage.error(response.msg)
  }
}
// 登录成功
const loginSuccess = async (response) => {
  // 判断是不是已登录 异地登录
  if (dialogTableVisible.value) {
    const arg = {
      messageContent: '账号在别处登录',
      messageType: 7, // 账号在别处登录 强制下线
      messageCode: 1, // 1发送给用户 2发送给群聊
      contactId: alreadyLoginResponse.value.data.userInfo.userId
    }
    const res = await Api.sendMessage(arg)
    if (res.code === 200) {
      openMainWindows(alreadyLoginResponse.value) // 打开主窗口
    }
  } else {
    openMainWindows(response)
  }
}

// 登录成功 调整主窗口的宽高
const openMainWindows = async (response) => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: '#ffffff'
  })

  dialogTableVisible.value = false // 关闭异地登录提示窗口
  userInfoStore.setUserInfo(response.data.userInfo, true) // 设置用户信息
  contactInfoStore.setContactInfoList(response.data.contactList) // 设置联系人列表

  // 设置黑名单列表
  let arr = []
  for (let i = 0; i < response.data.contactList.length; i++) {
    let val = response.data.contactList[i]
    for (let j = 0; j < val.value.length; j++) {
      //friendsCode 0:非好友 1:好友 2:已删除好友 3:被好友删除 4:已拉黑好友 5:被好友拉黑
      if (val.value[j].friendsCode === 4) {
        arr.push(val.value[j])
      }
    }
  }
  contactInfoStore.setContactBlacklistList(arr)
  // 设置好友申请列表
  setContactApplyList(response.data.contactApplyList)

  // 发送给主进程登录成功 主进程初始化
  window.ipcRenderer.send('loginSuccess', {
    userInfo: response.data.userInfo,
    wsIp: import.meta.env.VITE_WS_URL
  })
  // 判断是否有离线消息
  if (response.data.offlineMessages.length > 0) {
    // 保存离线消息 没有接收到的消息
    try {
      // 保存离线消息 没有接收到的消息
      const data = await window.ipcRenderer.invoke(
        'saveOfflineMessages',
        clone(response.data.offlineMessages)
      )
      if (!data) {
        ElMessage.error('登录失败 保存离线消息失败')
        loading.close()
        return
      }
    } catch (error) {
      ElMessage.error('登录失败 保存离线消息失败')
      loading.close()
      return
    }
  }
  // 统一的登录成功逻辑
  setTimeout(() => {
    router.push('/main') // 跳转到主页
    setTimeout(() => {
      loading.close()
    }, 500)
  }, 1000)
}

const setContactApplyList = (data) => {
  let newFriendApplyList = []
  for (let i = 0; i < data.length; i++) {
    // 遍历数组
    let info = data[i] // 获取元素
    let a = JSON.parse(info.applyContent) // 将json字符串转换为 对象
    let c = {
      // 创建对象
      applyTime: info.applyTime,
      applyStatus: info.applyStatus,
      contactApplyUserInfo: a.contactApplyUserInfo,
      contactApply: a.contactApply,
      contactUserInfo: a.contactUserInfo,
      type: a.type,
      contactApplyId: info.contactApplyId
    }
    newFriendApplyList.push(c) // 添加对象
  }
  newFriendStore.setNewFriend(newFriendApplyList) // 更新本地存储
}

/**
 * 验证字符长度
 * @returns {boolean}
 * @constructor
 */
const VerifyCharacterLength = () => {
  if (fromData.value.nickName.length > 15) {
    fromData.value.nickName = fromData.value.nickName.substring(0, 15)
    ElMessage.error('用户昵称长度不能超过15个字符')
    return false
  }
}
</script>
<style lang="scss" scoped>
.loading-panel {
  position: absolute;
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 2;
}

.login-panel {
  display: flex;
  flex-direction: column;
  align-items: center;

  .title {
    margin-top: 5px;
    display: flex;
    width: 100%;
    font-size: 15px;
    height: 25px;
    align-items: center;
    justify-content: start;
    padding-left: 10px;
  }

  .login-form {
    //margin: 0 auto;
    text-align: center;
    padding: 25px;
    width: 300px;
    background: white;
    border-radius: 10px;

    :deep(.el-input__wrapper) {
      padding-left: 5px;
      box-shadow: none;
      border-bottom: 1px solid #ddd;
    }
  }

  .captcha-container {
    display: flex;

    .captcha-img {
      cursor: pointer;
      flex: 1;
      width: 120px;
      height: 40px;
      margin-left: 2px;
    }

    .el-input {
      width: 130px;
    }
  }

  .login-btn {
    width: 100%;
  }

  .qq-login {
    width: 30px;
    height: 30px;
  }
}

.card2 {
  width: 100%;
  height: 100%;
  float: left;
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.8);

  .button {
    margin-top: 15px;
    display: flex;
    align-items: center;
    justify-content: center;

    .el-button {
      width: 100px;
    }
  }
}

.a-link {
  cursor: pointer;

  &:hover {
    color: #436895;
  }
}
</style>
